<?php

class ContactAdminController extends GxController {

    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('getMessage', 'sendMailTouser'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('inbox'),
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }	
	
	public function actionInbox() {
        $this->layout = 'detailspage';
		$backenduserDetails = '';
        $criteria = new CDbCriteria;
        $criteria->condition = 'from_users_id = ' . getLoginUserId();
        $inboxAll = ContactAdmin::model()->findAll($criteria);
		$backenduserDetails = Profiles::model()->findByAttributes(array('user_id' => Message::ADMIN_ID));
		$this->render('inbox', array('inbox' => $inboxAll,'backenduserDetails'=>$backenduserDetails));
    }
	
	
	 public function actionGetMessage() {
		$userdata = "";
		$resulData = "";
        $criteria = new CDbCriteria;
        $criteria->condition = '(backend_user_id = ' . Message::ADMIN_ID . ' AND from_users_id =' . getLoginUserId() . ')';
        $dataByUser = ContactAdmin::model()->findAll($criteria);
        if(count($dataByUser)>0){
        echo '<p class="subject-head"><span>Subject:</span> ' . $dataByUser[0]->subject . '</p><div class="height1px dash-borB addmarginB20 rempaddingB"></div><div class="commentBox"><ol>';
        $totalCount = count($dataByUser) - 1;
        for ($i = 0; $i < count($dataByUser); $i++) {
            $userDetails = Profiles::model()->findByAttributes(array('user_id' => $dataByUser[$i]->from_users_id));
            $imagePath = $dataByUser[$i]->from_users_id;
            if ($userDetails->photo <> "") {
                $imgsrc = baseUrl() . '../../' . getUploadDir() . $imagePath . '/profile/minithumb/' . $userDetails->photo;
            } else {
                $imgsrc = baseUrl() . '../../upload/default-mini.png';
            }

            $userdata.='<li><div class="padding"><div class="user-info borB"><p><img class="user-img" src="' . $imgsrc . '" title="' . $userDetails->first_name . '" alt="' . $userDetails->first_name . '" />' . $userDetails->first_name . '<p><span class="commentDateStamp">' . date("D, d M Y", convert_datetime($dataByUser[$i]->created)) . '</span></p></div><div class="comment"><p>' . $dataByUser[$i]->query . '</p>' . '</div></div></li>';
                $resulData = $userdata . $sendMsgBlock = '</ol></div>
					<input type="hidden" name="subject" id="subject_adminid" value="' . $dataByUser[$i]->subject . '">
					<div id="send_a_msg_box" class="reply-box">
					<textarea  id="message_text_adminid" name="message_text"></textarea>
					<div  class="errorMessage" id="errorMessage_subject_adminid"></div>
					<div class="clear"></div>
					</div>												
					<p class="alignR remmarginB">
					<input type="button" value="Submit" name="yt1" class="btnbook" onclick="return replyAMailToUserAdmin()"></p>
					</div>';
        }
		}else{
		
		$resulData = '<input type="text" name="subject" id="subject_adminid" placeholder="Subject*" value="">
					<div  class="errorMessage" id="errorMessage_subject_adminid"></div>
					<div id="send_a_msg_box" class="reply-box">
					<textarea  id="message_text_adminid" name="message_text" placeholder="Message*"></textarea>
					<div  class="errorMessage" id="errorMessage_msg_adminid"></div>
					<div class="clear"></div>
					</div>												
					<p class="alignR remmarginB">
					<input type="button" value="Submit" name="yt1" class="btnbook" onclick="return replyAMailToUserAdmin()"></p>';
		}
		
        echo $resulData;
    }
	
	
	 public function actionsendMailTouser() {

        if (isset($_POST['msgval'])) {
                $model = new ContactAdmin;
                $model->setAttribute('backend_user_id', Message::ADMIN_ID);
                $model->setAttribute('subject', $_POST['subject']);
                $model->setAttribute('query', $_POST['msgval']);
                $model->setAttribute('from_users_id', getLoginUserId());
                $model->setAttribute('created', SkillConfig::CreateDateTime());
                $userdetails = Users::getFrontEndUser(Message::ADMIN_ID);
                $trainername = Users::getFrontEndUser(getLoginUserId());
                $model->save();
                $mailmodel = EmailTemplate::model()->findByPk(Message::CONTACT_ADMIN_NOTIFICATION);
                $userText = $mailmodel->body;
                $mailbody = array('value' => $userText, 'type' => 'raw');
                $userName = $userdetails->first_name . ' ' . $userdetails->last_name;
                $trainernames = $trainername->first_name . ' ' . $trainername->last_name;
                $mailto = $userdetails->user->username;
                $arrayFind = array('[username]', '[from_user_name]', '[message]');
                $arrayReplace = array($userName, $trainernames, $_POST['msgval']);
                $mailbody = str_replace($arrayFind, $arrayReplace, $mailbody);
                $mailtemp = Template::model()->findByPk($mailmodel->template_id);
                $subject = $mailmodel->subject;
                $body = $this->renderPartial('/mails/' . $mailtemp->filename, array('mailbody' => $mailbody['value']), true, false);
                try {
                    /*SkillSendMail::SendMail($mailto, $subject, $body);*/
                    $result = 'success';
                } catch (Exception $e) {
                    $result = $e;
                    exit;
                }
            if ($result == 'success') {
                echo 'success';
            }
            Yii::app()->end();
        }
    }
	

}